using B.S.XZYData.Api.Wrter.Application.Command.SalesOrder;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using SqlSugar;
using SalesOrderEntity = B.S.XZYData.Domain.XZY.SalesOrder;
using SalesOrderProductEntity = B.S.XZYData.Domain.XZY.SalesOrderProduct;

namespace B.S.XZYData.Api.Wrter.Application.Handler.SalesOrder
{
    /// <summary>
    /// 更新销售订单处理器
    /// </summary>
    public class UpdateSalesOrderHandler : IRequestHandler<UpdateSalesOrderCommand, ApiResult<string>>
    {
        private readonly IBaseRepository<SalesOrderEntity> _salesOrderRepo;
        private readonly IBaseRepository<SalesOrderProductEntity> _salesOrderProductRepo;

        public UpdateSalesOrderHandler(
            IBaseRepository<SalesOrderEntity> salesOrderRepo,
            IBaseRepository<SalesOrderProductEntity> salesOrderProductRepo)
        {
            _salesOrderRepo = salesOrderRepo;
            _salesOrderProductRepo = salesOrderProductRepo;
        }

        public async Task<ApiResult<string>> Handle(UpdateSalesOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 检查销售订单是否存在
                var existingOrder = await _salesOrderRepo.GetValue(request.Id);
                if (existingOrder == null)
                {
                    return ApiResult<string>.Error("销售订单不存在");
                }

                // 检查单据编号是否重复（排除当前订单）
                if (!string.IsNullOrEmpty(request.OrderNo))
                {
                    var duplicateOrder = await _salesOrderRepo.GetAllAsync(x => 
                        x.OrderNo == request.OrderNo && 
                        x.Id != request.Id && 
                        !x.IsDeleted);
                    
                    if (duplicateOrder.Any())
                    {
                        return ApiResult<string>.Error("单据编号已存在");
                    }
                }

                // 更新销售订单基本信息
                existingOrder.OrderNo = request.OrderNo ?? existingOrder.OrderNo;
                existingOrder.Remark = request.Remark;
                existingOrder.ModifyTime = DateTime.Now;
                existingOrder.ModifierId = 1; // 这里应该从当前用户上下文获取

                await _salesOrderRepo.UpdateAsync(existingOrder);

                // 删除原有的产品明细（软删除）
                var existingProducts = await _salesOrderProductRepo.GetAllAsync(x => 
                    x.SalesOrderId == request.Id && !x.IsDeleted);
                
                foreach (var product in existingProducts)
                {
                    product.IsDeleted = true;
                    product.ModifyTime = DateTime.Now;
                    product.ModifierId = 1; // 这里应该从当前用户上下文获取
                    await _salesOrderProductRepo.UpdateAsync(product);
                }

                // 添加新的产品明细
                var newProducts = request.Products.Select(p => new SalesOrderProductEntity
                {
                    SalesOrderId = request.Id,
                    ProductCode = p.ProductCode,
                    ProductName = p.ProductName,
                    ProductSpec = p.ProductSpec,
                    WorkOrderNo = p.WorkOrderNo,
                    Quantity = p.Quantity,
                    CompletedQuantity = 0, // 新增时默认完成数量为0
                    CreateTime = DateTime.Now,
                    CreatorId = 1, // 这里应该从当前用户上下文获取
                    ModifyTime = null, // 新增时修改时间为空
                    ModifierId = null, // 新增时修改人为空
                    IsDeleted = false
                }).ToList();

                await _salesOrderProductRepo.CreateBatchAsync(newProducts);

                return ApiResult<string>.Success("更新成功");
            }
            catch (Exception ex)
            {
                return ApiResult<string>.Error($"更新销售订单失败：{ex.Message}");
            }
        }
    }
}
